﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class ReviewPostRequest : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            mtvRequest.SetActiveView(vRequests);
        }

        protected void BtnShowUnShowClick(object sender, EventArgs e)
        {
            if (Request.Form["chkItem"] == null) return;

            string selectedItems = Request.Form["chkItem"];
            string[] selectedItemIds = selectedItems.Split(',');
            foreach (StudentRequest studentRequest in selectedItemIds.Select(t => new Guid(t)).Select(itemId => StudentRequestServices.GetById(itemId)))
            {
                studentRequest.IsChecked = !studentRequest.IsChecked;

                StudentRequestServices.SaveOrUpdate(studentRequest);
            }

            gridData.DataBind();
            udpGrid.DataBind();
        }

        protected void BtnOpenCloseClick(object sender, EventArgs e)
        {
            if (Request.Form["chkItem"] == null) return;

            string selectedItems = Request.Form["chkItem"];
            string[] selectedItemIds = selectedItems.Split(',');
            foreach (StudentRequest studentRequest in selectedItemIds.Select(t => new Guid(t)).Select(itemId => StudentRequestServices.GetById(itemId)))
            {
                studentRequest.IsClosed = !studentRequest.IsClosed;

                StudentRequestServices.SaveOrUpdate(studentRequest);
            }

            gridData.DataBind();
            udpGrid.DataBind();
        }

        protected void BtnDeleteClick(object sender, EventArgs e)
        {
            if (Request.Form["chkItem"] == null) return;

            string selectedItems = Request.Form["chkItem"];
            string[] selectedItemIds = selectedItems.Split(',');
            foreach (var itId in selectedItemIds.Select(itemId => new Guid(itemId))) StudentRequestServices.Delete(itId);

            gridData.DataBind();
            udpGrid.DataBind();
        }

        protected void GridDataItemCommand(object sender, CommandEventArgs e)
        {
            string commandName = e.CommandName;
            string commandArgument = e.CommandArgument.ToString();

            if (commandArgument == string.Empty) return;

            var guidId = new Guid(commandArgument);
            StudentRequest studentRequest = StudentRequestServices.GetById(guidId);

            switch (commandName)
            {
                case "Delete":
                    StudentRequestServices.Delete(studentRequest);

                    break;
                case "Show":
                    studentRequest.IsChecked = true;
                    StudentRequestServices.SaveOrUpdate(studentRequest);
                    //SendReviewedPostEmail(studentRequest);
                    SendEmail(studentRequest);

                    break;
                case "UnShow":
                    studentRequest.IsChecked = false;
                    StudentRequestServices.SaveOrUpdate(studentRequest);

                    break;
                case "Open":
                    studentRequest.IsClosed = false;
                    StudentRequestServices.SaveOrUpdate(studentRequest);

                    break;
                case "Close":
                    studentRequest.IsClosed = true;
                    StudentRequestServices.SaveOrUpdate(studentRequest);

                    break;
                case "Edit":

                    Page.CloseMessage(lblMsg);
                    txtTitle.Text = studentRequest.Title;
                    txtContent.Text = studentRequest.Content;
                    hdfContentId.Value = studentRequest.ID.ToString();

                    mtvRequest.SetActiveView(vEditRequest);
                    break;
                //default:
                //    Response.Redirect("Default.aspx");
                //    break;
            }
            udpGrid.DataBind();
        }

        #region Edit Request Events
        protected void BtnSaveClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            try
            {
                StudentRequest studentRequest = StudentRequestServices.GetById(new Guid(hdfContentId.Value));

                studentRequest.Title = txtTitle.Text;
                studentRequest.Content = txtContent.Text;

                StudentRequestServices.SaveOrUpdate(studentRequest);

                ClearInputFields();
                Page.DisplayMessage(lblMsg, "Cập nhật thành công!", MessageType.Success);
                btnCancel.Text = "Đóng";
            }
            catch (Exception ex)
            {
                Logger.Debug(ex.Message);
                Page.DisplayMessage(lblMsg, "Cập nhật không thành công. Vui lòng cập nhật lại sau", MessageType.Error);
            }
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            txtTitle.Text = string.Empty;
            txtContent.Text = string.Empty;
            hdfContentId.Value = string.Empty;

            gridData.DataBind();
            mtvRequest.SetActiveView(vRequests);
        }
        #endregion

        #region Private Methods
        private void SendEmail(StudentRequest stdRequest)
        {
            IList<Teacher> sbTeachers = TeacherServices.GetSubcribeTeachers(stdRequest.Subject);

            var agrs = new object[] { stdRequest, sbTeachers };
            System.Threading.ThreadPool.QueueUserWorkItem(SendSubcribeEmails, agrs);
        }

        private void SendSubcribeEmails(object state)
        {
            var args = state as object[];

            if (args == null) return;
            var studentRequest = args[0] as StudentRequest;
            IList<Teacher> teachers = args[1] as List<Teacher>;

            SendReviewedPostEmail(studentRequest);

            // ReSharper disable PossibleNullReferenceException
            string baseMail = "<div style=\"text-align: justify;\">{0}</div><br /><div>";
            baseMail += "<label style=\"font-weight: bold;\"> LƯU Ý:</label><br /><ul>";
            baseMail += "<li>Bạn có thể nhấp chuột vào đường dẫn bên dưới để xem chi tiết.<br />";
            baseMail += "<a href=\"{1}\">{1}</a></li>";
            baseMail += "<li>Bạn có thể hủy việc đăng ký nhận tin tức mới qua email bấc cứ lúc nào bằng cách nhấp chuột vào đường dẫn dưới đây.<br />";
            baseMail += "<a href=\"{2}\">{2}</a></li></ul></div>";

            string reqDtlUrl = string.Format("{0}/StudentRequestDetails.aspx?itid={1}", SiteUrl, studentRequest.ID);
            foreach (Teacher teacher in teachers)
            {
                var unSubcribeUrl = string.Format("{0}/unsubscribe.aspx?tchid={1}", SiteUrl, teacher.ID);
                var mailContent = string.Format(baseMail, studentRequest.Content, reqDtlUrl, unSubcribeUrl);

                EmailSender.SendMailAsync(string.Format("Hi!Teachers - {0}", studentRequest.Title), mailContent, teacher.Email);
            }
            // ReSharper restore PossibleNullReferenceException
        }

        public void SendReviewedPostEmail(StudentRequest stdRequest)
        {
            string tmpPath = Server.MapPath("/mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["PostRequestReviewed"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.PostReviewedEmailBuilder(Convert.ToString(rows[0]["Content"]), stdRequest.Name);

            EmailSender.SendMail(subject, contentMail, stdRequest.Email);
        }

        private void ClearInputFields()
        {
            txtTitle.Text = string.Empty;
            txtContent.Text = string.Empty;
            hdfContentId.Value = string.Empty;
        }
        #endregion
    }
}